package com.web_bloks.dom.client;

import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;

/**
 * Utility class to retrieve <code>meta</code>
 * properties from the host DOM.
 * 
 * @author Jean-Lou Dupont
 *
 * Usage: 
 * 1) get singleton instance through factory
 * 2) use <code>getMeta</code> for each property
 *
 */
public class MetaProperties {

	HashMap<String,String> props = null;
	
	/**
	 * CTOR
	 */
	protected MetaProperties(){}
	
	
	/**
	 * GETTER for property
	 * 
	 * Usage (host file):
	 * 
	 * <code>
	 * 	<meta name="gwt:property" content="key=value"/>
	 * </code>
	 * 
	 * @param key
	 * @return
	 */
	public String getMeta(String key) {

		//lazy init
		if (null==props)
			init();
		
		if (!props.containsKey(key))
			return null;
		
		return props.get(key);
	}//
	
	/**
	 * Lazy init
	 */
	@SuppressWarnings("unchecked")
	protected void init() {
		
		if (null==props) {
			props = (HashMap<String, String>) GWT.create( MetaProperties.class );
		}
	
		Document doc = GWT.create( Document.class );
		NodeList<Element> list = doc.getElementsByTagName( "gwt:property" );
		
		if (null==list)
			return;
		
		for (int i=0;i<list.getLength();i++) {
			
			Element e = list.getItem( i );
			String content = e.getAttribute( "content" );
			if (null==content)
				continue;
			
			// key = value
			
			String[] bits = content.split( "=" );
			if ( 2 != bits.length )
				continue;
			
			props.put( bits[0], bits[1] );
		}
		
	}//
	
	
}//END